<template>
    <a-card :border="false">
        <a-spin :spinning="spanLoading">
          <div class="table-page-search-wrapper">
            <a-form layout="inline" :form="form">
                <a-row :gutter="[20, 20]">
                    <a-col :md="6" :sm="24">
                        <a-form-item label="名称">
                            <a-input placeholder="请输入名称" v-decorator="['storePackageName']" @pressEnter="loadData(1)" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <a-form-item label="门店包Id">
                            <a-input placeholder="请输入门店包Id" v-decorator="['storePackageId']" @pressEnter="loadData(1)" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item label="创建时间">
                            <a-range-picker v-decorator="['createTime']" :show-time="true"
                                format="YYYY-MM-DD HH:mm:ss" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <a-form-item label="状态">
                            <a-select  v-decorator="['status']" placeholder="全部">
                                <a-select-option v-for="item in statusList" :key="item.key" :value="item.key">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="18" :sm="24">
                        <a-button class="btn" type="primary" @click="search">搜索</a-button>
                        <a-button class="btn" type="primary" @click="reset">重置</a-button>
                        <a-button class="btn" type="primary" :loading="btnLoading" @click="asyncData">同步数据</a-button>
                        <a-button type="primary" @click="addStorePackage">新建门店包</a-button>
                    </a-col>
                </a-row>
            </a-form>
            </div>
            <a-table bordered :columns="columns" :rowKey="record => record.id" :data-source="dataSource"
                :pagination="pagination" :scroll="{ x: true }" @change="handleTableChange" :loading="loading">

                <span slot="status" slot-scope="text, record">{{ record.status == '0' ? '启用' : '禁用' }}</span>
                <template slot="actions" slot-scope="text, record">
                    <a-button type="link" @click="handleEdit(record.id)">编辑</a-button>
                    <a-button type="link" @click="copyPackage(record.id)">复制</a-button>
                    <a-button type="link" @click="updatePackageStatus(record)">{{ record.status == '0' ? '禁用' : '启用' }}
                    </a-button>
                    <a-button type="link" @click="downLoadPackage(record.id)">下载</a-button>
                    <a-button type="link" @click="deleteStorePackage(record.id)">删除</a-button>
                </template>
            </a-table>
        </a-spin>
        <Down />
    </a-card>
</template>

<script>
import { listMixin } from '../../micromall/util/listMixin'
import Down from '../components/down.vue'
import { postAction } from '@/api/manage'
import { queryResult } from '@/api/micromall/box.js'
import { updpateStorePackageStatus, deleteStorePackage, downloadPackage, asynOpenData } from '@/api/micromall/storePackage'
import moment from 'moment'
const columns = [
    {
        title: '门店ID',
        width: 100,
        align: 'center',
        dataIndex: 'storePackageId'
    },
    {
        title: '门店包名称',
        width: 100,
        align: 'center',
        dataIndex: 'storePackageName'
    },
    {
        title: '创建时间',
        width: 180,
        align: 'center',
        dataIndex: 'createTime'
    },
    {
        title: '编辑时间',
        width: 180,
        align: 'center',
        dataIndex: 'updateTime'
    },
    {
        title: '状态',
        width: 100,
        align: 'center',
        scopedSlots: { customRender: 'status' }
    },
    {
        title: '操作',
        width: 250,
        align: 'center',
        scopedSlots: { customRender: 'actions' }
    },
]
export default {
    name: '',
    mixins: [listMixin],
    data() {
        return {
            statusList: [{ key: 0, name: '启用' }, { key: 1, name: '禁用' },],
            btnLoading: false,
            loading: false,
            columns,
            dataSource: [],
            url: {
                list: '/jic-backend-activity/store/package/page'
            },
            count: 0,
            spanLoading: false
        }
    },
    components: {
        Down
    },
    methods: {
        async downLoadPackage(id) {
            const res = await downloadPackage({ id })
            if (res.code == 200) {
                this.$message.success('数据下载中，请在“下载中心”查看任务进度～')
            } else {
                this.$message.error(res.msg)
            }
        },
        async deleteStorePackage(id) {
            this.$confirm({
                title: '提示',
                content: '确认要删除该门店包吗',
                onOk: async () => {
                    const res = await deleteStorePackage(id)
                    if (res.code == 200) {
                        this.$message.success('删除成功')
                        this.loadData()
                    } else {
                        this.$message.error(res.msg)
                    }
                },
                onCancel() { },
            })


        },
        async updatePackageStatus(record) {
            let { status, id } = record
            status = status == '0' ? '1' : '0'
            const res = await updpateStorePackageStatus({ id, status })
            if (res.code == 200) {
                this.loadData()
                // this.$message.success('')
            }
        },
        loadData(arg) {
            if (!this.url.list) {
                this.$message.error('请设置url.list属性!')
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.pagination.current = 1
            }
            var params = this.getQueryParams() //查询条件
            if (params.createTime) {
                const [startTime, endTime] = params.createTime
                params.startTime = moment(startTime).format('YYYY-MM-DD HH:mm:ss')
                params.endTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss')
                delete (params.createTime)
            }
            this.spanLoading = true
            postAction(this.url.list, params).then(res => {
                this.spanLoading = false
                if (res.code == 200) {
                    //update-end---author:wsp    Date:20210826
                    this.dataSource = res.data.records || res.data
                    if (res.data.total) {
                        this.pagination.total = res.data.total
                    } else {
                        this.pagination.total = 0
                    }
                } else {
                    this.$message.warning(res.msg)
                }
                this.loading = false
            }).catch(err => {
                this.spanLoading = false
                console.log(err)
            })
        },
        copyPackage(id) {
            this.$router.push(`/marketingCenter/otherTools/storePackage/edit?id=${id}&isCopy=true`)
        },
        handleEdit(id) {
            this.$router.push(`/marketingCenter/otherTools/storePackage/edit?id=${id}`)
        },
        addStorePackage() {
            this.$router.push('/marketingCenter/otherTools/storePackage/edit')
        },
        async asyncData() {
            const res = await asynOpenData()
            const { code, msg, message, data } = res
            // if (code == 200) {
            //     this.$message.success('同步成功')
            // } else {
            //     this.$message.error(msg || message)
            // }
            if (code == 200 && data) {
                this.btnLoading = true
                this.loopTimer = setInterval(this.loopResult, 3000, data)
            } else {
                this.btnLoading = false
                this.$message.error(msg || message)
            }
        },
        clear() {
            this.btnLoading = false
            clearInterval(this.loopTimer)
            this.loopTimer = null
        },
        async loopResult(key) {
            if (this.count >= 30) {
                this.clear()
                return
            }
            this.count++
            const result = await queryResult({ key })
            if (result.data !== 'wait') {
                this.clear()
                if (result.data === 'storeSuccess') {
                    this.$message.success('同步成功')
                }
            }
        },
        reset() {
            this.form.resetFields()
            this.loadData(1)
        },
        search() {
            this.loadData(1)
        },
        close(id) {

        },
        open(id) {

        },
        deletePackage() {

        }
    },
    beforeDestroy() {
        this.clear()
    },
}
</script>

<style scoped>
.btn {
    margin-right: 10px;
}
</style>
